﻿using System;
using System.Drawing;
using System.Web;

namespace DflyingForum.Core.Framework
{
    /// <summary>
    /// 验证码辅助类
    /// </summary>
    public class ValidateCode
    {
        //随即生成验证字符串
        public void InitCharToOutPut(int num)
        {
            char[] validateChar = new char[] 
            { 
                '0','1','2','3','4','5','6','7','8','9',//num
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',//英文字母
                'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                '+','-','*','/','%','&','$','#','@','!','~',//特殊符号
                '论','坛','中','国','人','民','共','和','国','华','和','谐','断','鸣','助','樱','越','月','汉','字'//汉字
            };
            Random random = new Random();
            string validateCode = string.Empty;
            for (int i = 0; i < num; i++)
            {
                char rc = validateChar[random.Next(0, validateChar.Length)];
                validateCode += rc;
            }
        }

        //生成图片
        public void CreateValidateImg(string validateCode, string imgPath)
        {
            Bitmap bitmap = new Bitmap(Image.FromFile(imgPath), new Size(100, 80));
            Graphics g = Graphics.FromImage(bitmap);
            Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Chocolate, Color.Brown, Color.DarkCyan, Color.Purple };
            Random rand = new Random();
            for (int i = 0; i < validateCode.Length; i++)
            {
                int cindex = rand.Next(7);
                Font f = new System.Drawing.Font("Microsoft Sans Serif", 11);
                Brush b = new System.Drawing.SolidBrush(colors[cindex]);
                g.DrawString(validateCode.Substring(i, 1), f, b, (i * 10) + 1, 0, StringFormat.GenericDefault);
            }
            //画一个边框
            g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, bitmap.Width - 1, bitmap.Height - 1);

            //输出到浏览器
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/jpeg";
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            bitmap.Dispose();
        }
    }
}
